//
//  AllGoodsController.m
//  YiBaoStore
//
//  Created by 毛云河 on 2018/11/26.
//  Copyright © 2018 小河. All rights reserved.
//

#import "AllGoodsController.h"

@interface AllGoodsController ()<SLSlideMenuProtocol,
                                 UITableViewDelegate,
                                 UITableViewDataSource>

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UILabel *categroyLabel;//类别label
@property (nonatomic, strong) UIImageView *sanjiaoIcon;//小三角箭头
@property (nonatomic, strong) NSMutableArray *caterroyArray;//类别数据源
@property (nonatomic, assign) NSInteger select_classBtn_index;//记录选择的类别btn

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, copy) NSString *nextPageInfo;

@property (nonatomic, copy) NSString *searchCateroy;//选取类别查询

@end

@implementation AllGoodsController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //1.设置导航
    [self setNav];
    //2.创建顶部view
    [self createTopView];
    //3.创建表视图
    [self createTableView];
    
    self.searchCateroy = @"0";
    
    self.dataArray = [NSMutableArray array];
    self.caterroyArray = [NSMutableArray array];
    [self httpRequestAllShoppingData];
    [self httpRequsetGoodCategoryData];
}

- (void)httpRequsetGoodCategoryData
{
    __weak AllGoodsController *myself = self;
    [[HttpRequest currentHttpRequest]postPath:GoodsCategory_API params:@{} resultBlock:^(NSArray *Data, MsgModel *msgModel)
     {
         NSError *error;
         for (NSDictionary *dic in Data)
         {
             CategoryModel *model = [[CategoryModel alloc] initWithDictionary:dic error:&error];
             [myself.caterroyArray addObject:model];
         }
         NSLog(@"类别--%@",Data);
    }];
}


- (void)httpRequestNewData
{
    self.nextPageInfo = @"";
    self.dataArray = [NSMutableArray array];
    [self httpRequestAllShoppingData];
}

- (void)httpMoreData
{
    if (IsEmptyStr(self.nextPageInfo))
    {
        [self ShowHUDWithMessage:@"商品已全部加载，暂无更多"];
        [self.myTableView.mj_footer endRefreshingWithNoMoreData];
    }
    else {
        [self httpRequestAllShoppingData];
    }
    
}

- (void)httpRequestAllShoppingData
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.searchCateroy forKey:@"categoryId"];
    [dic setValue:@"1" forKey:@"isPlatform"];
    if (NOEmptyStr(self.nextPageInfo))
    {
        [dic setValue:self.nextPageInfo forKey:@"nextPageInfo"];
    }
        
    __weak AllGoodsController *myself = self;
    [HttpRequest formPostPath:SearchGoods_API params:dic resultBlock:^(NSDictionary *Data, MsgModel *msgModel)
    {
        NSLog(@"商品Data--%@",Data);
        NSDictionary *result = Data[@"result"];
        if (msgModel.status == 200)
        {
            myself.nextPageInfo = result[@"nextPageInfo"];
            NSArray *currentPageResult = result[@"currentPageResult"];
            NSLog(@"currentPageResult--%@",currentPageResult);
            
            NSError *error;
            if (currentPageResult.count == 0|| [currentPageResult[0] allKeys].count == 0)
            {
                [myself.myTableView.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                for (NSDictionary *dic in currentPageResult)
                {
                    MainModel *model = [[MainModel alloc] initWithDictionary:dic error:&error];
                    [myself.dataArray addObject:model];
                    NSLog(@"商品dic--%@",dic);
                }
            }
            [myself.myTableView.mj_header endRefreshing];
            [myself.myTableView.mj_footer endRefreshing];
            [myself.myTableView reloadData];
        }
        else {
            [myself.myTableView.mj_header endRefreshing];
            [myself.myTableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];

}

#pragma mark - 设置导航
- (void)setNav
{
    //显示右导航
    self.rightIcon.image = [UIImage imageNamed:@"sear_shopping"];
    self.rightIcon.hidden = NO;
    self.rightBtn.hidden = NO;
}

#pragma mark - 导航选择类别
- (void)rightBtnClick:(UIButton *)sender
{
    SearchController *seach = [[SearchController alloc] init];
    seach.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:seach animated:YES];
}

#pragma mark - 创建顶部view
- (void)createTopView
{
    self.topView = [[UIView alloc] init];
    [self.view addSubview:self.topView];
    self.topView.frame = CGRectMake(0, self.bgNavView.bottom, SCREENWIDTH, 38);
    self.topView.backgroundColor = [UIColor whiteColor];
    
    self.categroyLabel = [[UILabel alloc]init];
    [self.topView addSubview:self.categroyLabel];
    self.categroyLabel.frame = CGRectMake(15, 10, 30, 18);
    self.categroyLabel.textColor = BlackTextColor;
    self.categroyLabel.textAlignment = 0;
    self.categroyLabel.font = FontMediumWithSize(18);
    
    UIButton *categroyBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.topView addSubview:categroyBtn];
    categroyBtn.frame = CGRectMake(0, 0, 90, 38);
    [categroyBtn addTarget:self action:@selector(categroyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.sanjiaoIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sanjiao_goods"]];
    [self.topView addSubview:self.sanjiaoIcon];
    
    [self upLoadCategroyTitle:@"全部"];
}

#pragma mark - 刷新类别显示
- (void)upLoadCategroyTitle:(NSString *)categroy
{
    self.categroyLabel.text = categroy;
    [self.categroyLabel sizeToFit];
    self.sanjiaoIcon.frame = CGRectMake(self.categroyLabel.right+3, 14, 16, 16);
}

#pragma mark - 选择类别
- (void)categroyBtnClick:(UIButton *)sender
{
    NSDictionary *dic = @{@"key":@"test"};
    [SLSlideMenu slideMenuWithFrame:self.view.frame
                           delegate:self
                          direction:SLSlideMenuDirectionLeft
                        slideOffset:170
                allowSwipeCloseMenu:YES
                           aboveNav:YES
                         identifier:@"left" object:dic];
}

#pragma mark - 侧边栏添加子视图的代理
- (void)slideMenu:(SLSlideMenu *)slideMenu prepareSubviewsForMenuView:(UIView *)menuView
{
    if (slideMenu.direction == SLSlideMenuDirectionLeft)
    {
        UILabel *titltLabel = [[UILabel alloc] init];
        if (@available(iOS 11.0, *)) {
            titltLabel.frame = CGRectMake(15, 117+TopStatusHeight_xs, 100, 25);
        } else {
            // Fallback on earlier versions
            titltLabel.frame = CGRectMake(15, 117+TopStatusHeight, 100, 25);
        }
        [menuView addSubview:titltLabel];
        titltLabel.text = @"分类";
        titltLabel.font = FontMediumWithSize(18);
        titltLabel.textColor = BlackTextColor;
        titltLabel.textAlignment = 0;
        
        
        for (int i = 0; i < self.caterroyArray.count+1; i++)
        {
            UIImageView *imageIcon = [[UIImageView alloc] init];
            [menuView addSubview:imageIcon];
            imageIcon.frame = CGRectMake(15, (titltLabel.bottom+72)+(16+30)*(i/1), 16, 16);
            
            UILabel *label = [[UILabel alloc]init];
            [menuView addSubview:label];
            label.frame = CGRectMake(40, (titltLabel.bottom+72)+(16+30)*(i/1), 50, 16);
            label.font = FontWithSize(12);
            label.textColor = RGBACOLOR(66, 66, 66, 1);
            
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
            [menuView addSubview:btn];
            btn.frame = CGRectMake(0, (titltLabel.bottom+70)+(20+26)*(i/1), 170, 20);
            [btn addTarget:self action:@selector(btnSelectClick:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag = i+1;
            
            if (i == 0)
            {
                label.text = @"全部";
                if (i == self.select_classBtn_index)
                {
                    [btn setBackgroundImage:[UIImage imageNamed:@"btn_select_class"] forState:UIControlStateNormal];
                    label.textColor = RGBACOLOR(2, 2, 0, 1);
                }
            }
            else {
                CategoryModel *model = self.caterroyArray[i-1];
                label.text = model.name;
                [imageIcon sd_setImageWithURL:[NSURL URLWithString:model.logo] placeholderImage:[UIImage imageNamed:@"zhanwei100"]];
                
                if (i == self.select_classBtn_index)
                {
                    [btn setBackgroundImage:[UIImage imageNamed:@"btn_select_class"] forState:UIControlStateNormal];
                    label.textColor = RGBACOLOR(2, 2, 0, 1);
                    [imageIcon sd_setImageWithURL:[NSURL URLWithString:model.logoSelect] placeholderImage:[UIImage imageNamed:@"zhanwei100"]];
                }
            }
            
            
            
        }
    }
}

#pragma mark - 左菜单选择按钮
- (void)btnSelectClick:(UIButton *)sender
{
    //1,移除侧边栏
    [SLSlideMenu dismiss];
    
    //2,记录选择的类别
    self.select_classBtn_index = sender.tag - 1;
    
    if (sender.tag == 1)
    {
        self.searchCateroy = @"0";
        [self upLoadCategroyTitle:@"全部"];
    }
    else {
        //3,给navLeftBtn赋值
        CategoryModel *model = self.caterroyArray[self.select_classBtn_index-1];
        [self upLoadCategroyTitle:model.name];
        //4，刷新类目视图接口数据
        self.searchCateroy = model.ID;
    }
    
    [self httpRequestNewData];
}

#pragma mark - 创建表视图
- (void)createTableView
{
    if (@available(iOS 11.0, *))
    {
        self.myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.bgNavView.bottom+38, SCREENWIDTH, SCREENHEIGHT-self.topView.bottom-BottomHeight_xs) style:UITableViewStyleGrouped];
    } else {
        // Fallback on earlier versions
        self.myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.bgNavView.bottom+38, SCREENWIDTH, SCREENHEIGHT-self.topView.bottom-BottomHeight) style:UITableViewStyleGrouped];
    }
    self.myTableView.backgroundColor = RGBACOLOR(241, 241, 241, 1);
    [self.view addSubview:self.myTableView];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.sectionHeaderHeight = 0.01f;
    self.myTableView.sectionFooterHeight = 10.f;
    self.myTableView.tableFooterView = [self tableViewFoot];
    self.myTableView.tableHeaderView = [self tableViewHeader];
    
    [TTKUtil setAutomaticallyAdjustsScrollViewInsetsWidth:self.myTableView withView:self];
    [self.myTableView registerClass:[GoodsListCell class] forCellReuseIdentifier:@"GoodsListCell"];
    
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(httpRequestNewData)];
    self.myTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(httpMoreData)];
}

- (UIView *)tableViewHeader
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 0.01)];
    return view;
}

- (UIView *)tableViewFoot
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 0.01)];
    return view;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 375.f;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GoodsListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodsListCell"];
    cell.shanrkBtn.indexPath = indexPath;
    cell.changePriceBtn.indexPath = indexPath;
    cell.recommendBtn.indexPath = indexPath;
    [cell.shanrkBtn addTarget:self action:@selector(shanrkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.changePriceBtn addTarget:self action:@selector(changePriceBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.recommendBtn addTarget:self action:@selector(recommendBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.topTiteLabelBtn.indexPath = indexPath;
    cell.leftImageBtn.indexPath = indexPath;
    cell.rightImgaeBtn.indexPath = indexPath;
    [cell.topTiteLabelBtn addTarget:self action:@selector(gotoGoodsDeilt:) forControlEvents:UIControlEventTouchUpInside];
    [cell.leftImageBtn addTarget:self action:@selector(gotoGoodsDeilt:) forControlEvents:UIControlEventTouchUpInside];
    [cell.rightImgaeBtn addTarget:self action:@selector(gotoGoodsDeilt:) forControlEvents:UIControlEventTouchUpInside];
    
    MainModel *model = self.dataArray[indexPath.section];
    [cell setCellModel:model];
    
    return cell;
}

- (void)gotoGoodsDeilt:(UIButton *)sender
{
    NSLog(@"%@",@"前往商品详情页");
}

#pragma mark -分享按钮的绑定事件
- (void)shanrkBtnClick:(UIButton *)sender
{
    MainModel *model = self.dataArray[sender.indexPath.section];
    //前往分享商品视图
    SharkShoppingVC *shopping = [[SharkShoppingVC alloc] init];
    shopping.product_id = model.product_id;
    shopping.isHide = NO;
    [self.navigationController pushViewController:shopping animated:YES];
}

#pragma mark - 改价b绑定事件
- (void)changePriceBtnClick:(UIButton *)sender
{
    MainModel *model = self.dataArray[sender.indexPath.section];
    MYHAleartView *alertView = [[MYHAleartView alloc] initChangPriceWithModel:model];
    [alertView showAlertView];
    __weak AllGoodsController *myself = self;
    alertView.moneyBlock = ^(CGFloat number)
    {
        NSLog(@"%0.2f",number);
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:model.product_id forKey:@"itemId"];
        [dic setValue:[NSString stringWithFormat:@"%0.2f",number] forKey:@"price"];
        [HttpRequest formPostPath:EditGoods_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
         {
             NSLog(@"改价Data--%@",Data);
             [myself httpRequestNewData];
         }];

    };
}

#pragma mark - 推荐按钮绑定事件
- (void)recommendBtnClick:(UIButton *)sender
{
    MainModel *model = self.dataArray[sender.indexPath.section];
    MYHAleartView *alertView = [[MYHAleartView alloc] initMecommendAlertViewWithMessage:@"确认推荐该商品吗？" fuText:@"" sureBtnTitle:@"确认" cancleBtnTitle:@"取消"];
    [alertView showAlertView];
    NSInteger selectIndex = sender.indexPath.section;//当前数组索引
//    NSArray <NSIndexPath *> *indexPathArray = @[sender.indexPath];
    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:sender.indexPath.section];
    __weak AllGoodsController *myself = self;
    alertView.sureBlock = ^(id  _Nonnull sender)
    {
        NSLog(@"确认");
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:model.product_id forKey:@"itemId"];
        [HttpRequest formPostPath:AddRecommend_API params:dic resultBlock:^(NSDictionary *Data, MsgModel *msgModel)
         {
             NSLog(@"推荐商品Data--%@",Data);
             NSString *code = [NSString stringWithFormat:@"%@",(NSString *)Data[@"code"]];
             NSString *message = Data[@"message"];
             if ([code isEqualToString:@"-10000"])
             {
                 [myself ShowHUDWithMessage:message];
             }
             
             if (msgModel.status == 200)
             {
                 model.isShopRecommend = @"1";
                 [myself.dataArray replaceObjectAtIndex:selectIndex withObject:model];
                 [myself.myTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
             }
             
         }];
    };
}

@end
